package cn.ycc1.boot3http.util;

/**
 * @author ycc
 * @date 2024/9/9
 */
import okhttp3.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class HttpUtils {
    private static final OkHttpClient client = new OkHttpClient();

    public static String get(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", "Bearer your_token") // 添加授权头
                .build();

        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    public static String post(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));

        Request request = new Request.Builder()
                .url(url)
//                .addHeader("Authorization", "Bearer your_token") // 添加授权头
//                .addHeader("client-type", "CONSUMER")
//                .addHeader("shop-id", "0")
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        } catch (IOException e) {
            // 处理IO异常
            e.printStackTrace();
        } catch (Exception e) {
            // 处理OkHttp特定的异常
            e.printStackTrace();
        }
        return null;
    }
}

